/*
 * Copyright (C) 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org_rosjava.ros.android.android_tutorial_map_viewer;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.sun.shine.myrotation.view.ChangeDirListener;
import com.xuanfu_button.XuanfuButton_MapPointonLongClick;
import com.xuanfu_button.XuanfuButton_blank;
import com.zlp.mymapviewproject.mymapview.IMyMapPointListener;
import com.zlp.mymapviewproject.mymapview.MyMapView;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import net.xxhong.rosclient.R;
import org.jboss.netty.buffer.ChannelBuffer;
import org.ollide.rosandroid.ViewControlLayer;
import org.ollide.rosandroid.VirtualJoystickView2;
import org.ros.address.InetAddressFactory;
import org.ros.android.BitmapFromCompressedImage;
import org.ros.android.RosActivity;
import org.ros.android.view.MyRosTextSubscriber_Byte;
import org.ros.android.view.RosImageView;
import org.ros.android.view.visualization.TextureBitmap;
import org.ros.android.view.visualization.VisualizationView;
import org.ros.android.view.visualization.layer.CameraControlLayer;
import org.ros.android.view.visualization.layer.CameraControlListener;
import org.ros.android.view.visualization.layer.LaserScanLayer;
import org.ros.android.view.visualization.layer.Layer;
import org.ros.android.view.visualization.layer.OccupancyGridLayer;
import org.ros.android.view.visualization.layer.OccupancyGridLayer_mymap;
import org.ros.android.view.visualization.layer.PathLayer;
import org.ros.android.view.visualization.layer.PosePublisherLayer;
import org.ros.android.view.visualization.layer.PoseSubscriberLayer;
import org.ros.android.view.visualization.layer.RobotLayer;
import org.ros.node.NodeConfiguration;
import org.ros.node.NodeMainExecutor;
import org.ros.time.NtpTimeProvider;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import csy.menu.satellitemenulib.view.SatelliteMenu;
import geometry_msgs.PoseWithCovarianceStamped;
import nav_msgs.OccupancyGrid;
import sensor_msgs.CompressedImage;
import std_msgs.Byte;
import xia.Bean.Bean_from_slam_mark;
import xia.Bean.Change_content_tmpList;
import xia.MyMap_interface;
import xia.MySetPose_interface;
import xia.MyViewControlLayer_interface;
import xia.Ros_Connect;
import xia.SelfDialog_a1;
import xia.SelfDialog_m1;
import xia.XuanfuButton_Create;
import random_num_10.My_random_num_value;
import org.ros.android.view.MyRosTextSubscriber;
import org.ros.android.MessageCallable;
import static java.lang.Math.PI;
import org.ros.android.view.MyRos_sendTextPublish;
public class My_map extends RosActivity implements MyMap_interface , MyMapView.MyMapViewOnLongClickListener,IMyMapPointListener,ChangeDirListener, MyViewControlLayer_interface , MySetPose_interface {
  private static final String TAG = "My_map";
  public static SharedPreferences mSharedPreferences;
  public boolean is_at_move=false;
  public String mode="idle";
  public String user_mode="idle";
  public MyMapView myMapView;
  private boolean areLevel2Showing = false, areLevel3Showing_menu = false, areLevel3Showing_zoom = false, areLevel3Showing_direction = false;
  public boolean is_jinkia_direction_relativeLayout_show=false;
  private static RelativeLayout relate_my_ros_view_Layout2;
  private RelativeLayout my_ros_view_Layout_button;
  public TextView show_goto;
  public TextView show_status;
  public TextView show_dangqian;
  public EditText et_number;
  public Button sure_number;
  public ImageView battery;
  private static Button left_tools_direction;
  public static boolean is_first_Layout_show=true;
  public boolean if_need_change_point_direction=false;
  public boolean in_add_more_lines_flag=false;
  public boolean in_move_point_flag=false;
  public String in_add_more_lines_onClick_pointTitle_last="";
  public String in_set_wall_onClick_pointTitle_last="";
  ImageButton btnSubTopic;
  ImageButton btnCall;
  //private boolean isSubscribe = false;
  public boolean moving = false;
  public float linearX = 0;
  public float linearX_speed_change = 0.1f;
  public float linearX_speed_limt = 0.3f;//1f;//0.3f;
  public float angularZ_speed_limt =0.4f;// 1f;//0.4f;
  public int linearX_dir_flag = 1;
  public float angularZ = 0;
  public int angularZ_dir_flag = 1;
  int myDistanceLevel=0;
  Activity Context;
  public static My_map activity;
  public Double resolution = 0d;
  public Double resolution_position_x = 0d;
  public Double resolution_position_y = 0d;
  public int map_hight = 0;
  public int x_map = -1;
  public int y_map = -1;

  public boolean already_in_update_Dialog_flag = false;
  public XuanfuButton_blank xuanfuButton_blank;
  public XuanfuButton_MapPointonLongClick xuanfuButton_PointonLongClick;
  public FrameLayout.LayoutParams params_xuanfu;
  public boolean isAdded = false;
  public boolean is_first_wait_map = true;
  public boolean is_first_start_wait_mark_result_request = true;
  private Button quxiao;
  private Button ting;
  private Button jixu;
  public float marked_LongClickdown_fingerX=0;
  public float marked_LongClickdown_fingerY=0;
  public Double marked_positionInfo_x;
  public Double marked_positionInfo_y;
  public float marked_move_fingerX=0;
  public float marked_move_fingerY=0;
  public Double marked_positionInfo_x_move;
  public Double marked_positionInfo_y_move;
  public int xuanfu_x=0;
  public int xuanfu_y=0;
  public boolean is_at_mapping = false;
  public Bean_from_slam_mark mark_coordinatejsondata_last=null;
  public Bean_from_slam_mark mark_coordinatejsondata_last_tmp_for_change_content=null;
  public List<Change_content_tmpList> change_content_tmpListnew=new ArrayList<Change_content_tmpList>();
  public Thread downLoadThread;
  public boolean mark_coordinate_add_succeeded=false;
  public boolean mark_coordinate_del_succeeded=false;
  public boolean mark_line_change_succeeded=false;
  public boolean need_finsh=false;
  public boolean is_switch_ros_app_mapView_big=false;
  private RosImageView<CompressedImage> cameraView;
  private ViewGroup mainLayout;
  private ViewGroup sideLayout;
  private VirtualJoystickView2 virtualJoystickView;
  private MyRosTextSubscriber<std_msgs.String> myRosTextSubscriber;
  private MyRosTextSubscriber_Byte<Byte> myRosTextSubscriber_battery;
  private MyRosTextSubscriber_Byte<std_msgs.Byte> myRosTextSubscriber_navback;
  //private MyRosTextSubscriber_log<Log> myRosTextSubscriber_log;
  public MyRos_sendTextPublish  myRos_sendTextPublish;
  public int addPoint_number = 0;
  public  List<String>  markNamelist= new ArrayList<>();
  public  List<String>  namelist= new ArrayList<>();
  public static String point_type_flag="(-";
  private LinearLayout connectionLayout;
  ViewControlLayer viewControlLayer;
  private static final String MAP_FRAME = "map";
  private static final String ROBOT_FRAME = "base_link";
  private final SystemCommands systemCommands;
  private VisualizationView visualizationView;
  private CameraControlLayer cameraControlLayer;
  private ToggleButton showCameraToggleButton;
  public boolean is_need_edit_point_map_show_flag=false;
  OccupancyGridLayer myOccupancyGridLayer;
  OccupancyGridLayer_mymap myOccupancyGridLayer_mymap;
  public My_map() {
    super("Map Viewer", "Map Viewer");
    systemCommands = new SystemCommands();
  }
  PoseWithCovarianceStamped parseAmclTopic_message_last;
  private static String  password="";
  private static String mDefaultpassword = "123456";
  public String  requestedOrientation="hen";
  private static String  user_input_ip="";
  private SatelliteMenu  mSatelliteMenuLeftBottom;
  static int false_timeout_number = 0;
  Handler mHandler_get_log;
  static Thread mylisten_getlog_Thread;
  Runnable run_get_log_timeout = new Runnable() {
    @Override
    public void run() {
      false_timeout_number++;
      if(false_timeout_number >2) {
        false_timeout_number = 0;
        mylisten_getlog_Thread.interrupt();
        mylisten_getlog_Thread.stop();
        My_map.getinstance().finish();
      }
    }
  };
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activity = this;
    Context = this;
    //set_is_x(true);
    //set_is_user_input_ip_start(true);
    mHandler_get_log = new Handler();
    false_timeout_number = 0;
    mSharedPreferences = getSharedPreferences("myros", Activity.MODE_PRIVATE);
    if(mSharedPreferences!=null) {
      password = mSharedPreferences.getString("password", mDefaultpassword);
      requestedOrientation= mSharedPreferences.getString("Orientation", "shu");
      if(requestedOrientation.equals("hen"))
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
      else
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //竖屏
      user_input_ip= mSharedPreferences.getString("user_input_ip", "");
      if(!user_input_ip.equals(""))
        set_user_input_ip(user_input_ip);
      else
      {
        showInputDialog_setInput_ip();
      }
    }
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.my_map);
    cameraView = (RosImageView<CompressedImage>) findViewById(R.id.image);
    cameraView.setMessageType(CompressedImage._TYPE);
    cameraView.setMessageToBitmapCallable(new BitmapFromCompressedImage());
    virtualJoystickView = (VirtualJoystickView2) findViewById(R.id.virtual_joystick);
    myRosTextSubscriber=new MyRosTextSubscriber(this);
    myRosTextSubscriber.setTopicName("/multinav/work_mode_result");
    myRosTextSubscriber.setMessageType(std_msgs.String._TYPE);
    myRosTextSubscriber.setMessageToStringCallable(new MessageCallable<String, std_msgs.String>() {
      @Override
      public String call(final std_msgs.String message) {
        false_timeout_number = 0;
        mHandler_get_log.removeCallbacks(run_get_log_timeout);
        Ros_Connect.parseWork_mode_result(message.getData().toString());
        return message.getData();
      }
    });
    myRosTextSubscriber_battery=new MyRosTextSubscriber_Byte(this);
    myRosTextSubscriber_battery.setTopicName("/battery/level");
    myRosTextSubscriber_battery.setMessageType(Byte._TYPE);
    myRosTextSubscriber_battery.setMessageToByteCallable(new MessageCallable<Byte, std_msgs.Byte>() {
      @Override
      public Byte call(final Byte message) {
          runOnUiThread(new Runnable() {
            @Override
            public void run() {
              if(message.getData()>=0&&message.getData()<10)
                battery.setImageResource(R.drawable.power_0);
              else if(message.getData()>=10&&message.getData()<20)
                battery.setImageResource(R.drawable.power_1);
              else if(message.getData()>=20&&message.getData()<40)
                battery.setImageResource(R.drawable.power_2);
              else if(message.getData()>=40&&message.getData()<60)
                battery.setImageResource(R.drawable.power_3);
              else if(message.getData()>=60&&message.getData()<80)
                battery.setImageResource(R.drawable.power_4);
              else if(message.getData()>=80&&message.getData()<100)
                battery.setImageResource(R.drawable.power_5);
              if(message.getData()<10)
              {
                PlaySound(0);
              }
            }
          });
        return null;
      }});

    myRosTextSubscriber_navback=new MyRosTextSubscriber_Byte(this);
    myRosTextSubscriber_navback.setTopicName("/navback/button");
    myRosTextSubscriber_navback.setMessageType(Byte._TYPE);
    myRosTextSubscriber_navback.setMessageToByteCallable(new MessageCallable<Byte, std_msgs.Byte>() {
      @Override
      public Byte call(Byte message) {
          if(message.getData()==1&&My_map.getinstance().mark_coordinatejsondata_last!=null) {
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                for(int i=0;i<My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.size();i++)
                {
                  String name=My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).name;
                  if(name.equals("厨房"))
                  {
                    Float coordinate_0 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(0);
                    Float coordinate_1 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(1);
                    Float coordinate_2 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(2);
                    Float coordinate_3 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(3);
                    Float coordinate_4 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(4);
                    Float coordinate_5 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(5);
                    Float coordinate_6 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(6);
                    String get_name = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).name;
                    final String coordinate_string = String.valueOf(coordinate_0) + "," + String.valueOf(coordinate_1) + "," + String.valueOf(coordinate_2) + "," + String.valueOf(coordinate_3) + "," + String.valueOf(coordinate_4) + "," + String.valueOf(coordinate_5) + "," + String.valueOf(coordinate_6) ;
                    String data_value="simplenav:"+coordinate_string+ ":" + get_name;
                    My_map.getinstance().myRos_sendTextPublish.sendStringData(data_value);
                    PlaySound(3);
                    show_goto.setText("当前正前往：厨房");
                    break;
                  }
                }
              }
            });
          }
          return null;
      }});
    myRos_sendTextPublish=new MyRos_sendTextPublish("/multinav/work_mode_ctrl");
    visualizationView = (VisualizationView) findViewById(R.id.map_view);
    cameraControlLayer = new CameraControlLayer();
    myOccupancyGridLayer_mymap=new OccupancyGridLayer_mymap("map", this,true);
    visualizationView.onCreate(Lists.<Layer>newArrayList(
            cameraControlLayer,
            myOccupancyGridLayer_mymap,
            new LaserScanLayer("scan"),
            new PathLayer("move_base/GlobalPlanner/plan"),
            new RobotLayer(ROBOT_FRAME)
    ));
    enableFollowMe();
    visualizationView.getCamera().jumpToFrame("map");
    mainLayout = (ViewGroup) findViewById(R.id.main_layout);
    sideLayout = (ViewGroup) findViewById(R.id.side_layout);
    connectionLayout = (LinearLayout) findViewById(R.id.myconnection_layout);
    connectionLayout.setVisibility(View.VISIBLE);
    init_menu();
    //cameraView.setCamera_show(true,true);
  }
  void init_menu()
  {
    mSatelliteMenuLeftBottom = (SatelliteMenu) findViewById(R.id.mSatelliteMenuLeftBottom);
    List<String> nameMenuItem = new ArrayList<>();
    nameMenuItem.add("修改IP");
    nameMenuItem.add("改密码");
    nameMenuItem.add("横竖屏");
    List<Integer> imageResourceLeftBottom = new ArrayList<>();
    imageResourceLeftBottom.add(R.drawable.imag_tel);
    imageResourceLeftBottom.add(R.drawable.imag_msg);
    imageResourceLeftBottom.add(R.drawable.imag_pic);
    mSatelliteMenuLeftBottom.getmBuilder()
            .setMenuItemNameTexts(nameMenuItem)
            .setMenuImage(R.drawable.menu)
            .setMenuItemImageResource(imageResourceLeftBottom)
            .setOnMenuItemClickListener(new SatelliteMenu.OnMenuItemClickListener() {
              @Override
              public void onClick(View view, int postion) {
                if(postion==0)
                {
                  showInputDialog_setInput_ip();
                }
                else if(postion==1)
                {
                  showInputDialog_setpassword();
                }
                else if(postion==2)
                {
                  showInputDialog_switch_Orientation("确定要切换横竖屏吗？","start");
                }

              }
            })
            .creat();
  }
  @Override
  protected void init(NodeMainExecutor nodeMainExecutor) {
    viewControlLayer =
            new ViewControlLayer(this,
                    nodeMainExecutor.getScheduledExecutorService(), cameraView,
                    visualizationView, mainLayout, sideLayout,this);
    visualizationView.addLayer(viewControlLayer);
    visualizationView.addLayer(new PoseSubscriberLayer("move_base_simple/goal"));
    visualizationView.addLayer(new PosePublisherLayer("move_base_simple/goal",this));
    visualizationView.init(nodeMainExecutor);
    cameraControlLayer.addListener(new CameraControlListener() {
      @Override
      public void onZoom(float focusX, float focusY, float factor) {
        disableFollowMe();
      }
      @Override
      public void onDown() {
        disableFollowMe();
      }
      @Override
      public void onTranslate(float distanceX, float distanceY) {
        disableFollowMe();
      }
      @Override
      public void onRotate(float focusX, float focusY, double deltaAngle) {
        disableFollowMe();
      }
      @Override
      public void onDoubleTap(float x, float y) {
      }
    });

    NodeConfiguration nodeConfiguration =
            NodeConfiguration.newPublic(InetAddressFactory.newNonLoopback().getHostAddress(),
                    getMasterUri());
    NtpTimeProvider ntpTimeProvider =
        new NtpTimeProvider(InetAddressFactory.newFromHostString("192.168.0.1"),
            nodeMainExecutor.getScheduledExecutorService());
    ntpTimeProvider.startPeriodicUpdates(1, TimeUnit.MINUTES);
    nodeConfiguration.setTimeProvider(ntpTimeProvider);
    nodeMainExecutor.execute(visualizationView, nodeConfiguration);
    nodeMainExecutor.execute(systemCommands, nodeConfiguration);
    cameraView.setTopicName("/usb_cam/image_raw/compressed");
    virtualJoystickView.setTopicName("/cmd_vel");
    nodeMainExecutor.execute(cameraView, nodeConfiguration.setNodeName("android/camera_view"+My_random_num_value.random_num));
    nodeMainExecutor.execute(virtualJoystickView, nodeConfiguration.setNodeName("android/virtual_joystick"+My_random_num_value.random_num));
    nodeMainExecutor.execute(myRosTextSubscriber, nodeConfiguration.setNodeName("/multinav/work_mode_result"+My_random_num_value.random_num));
    nodeMainExecutor.execute(myRosTextSubscriber_battery, nodeConfiguration.setNodeName("/battery/level"+My_random_num_value.random_num));
    nodeMainExecutor.execute(myRosTextSubscriber_navback, nodeConfiguration.setNodeName("/navback/button"+My_random_num_value.random_num));
    nodeMainExecutor.execute(myRos_sendTextPublish, nodeConfiguration.setNodeName("/multinav/work_mode_ctrl"+My_random_num_value.random_num));
    My_map.getinstance().runOnUiThread(new Runnable() {
      @Override
      public void run() {
        connectionLayout.setVisibility(View.GONE);
        my_init();
      }
    });
  }
  public void setPoseClicked(View view) {
    setPose();
  }
  public void setGoalClicked(View view) {
    setGoal();
  }
  private void setPose() {
    PosePublisherLayer.setPoseMode();
    viewControlLayer.switch_show_ViewMode();
  }
  private void setGoal() {
    PosePublisherLayer.setGoalMode();
    viewControlLayer.switch_show_ViewMode();
  }
  void my_init()
  {
    AddSound();
    is_first_wait_map = true;
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    findViews();
    setListener();
    myMapView = (MyMapView) findViewById(R.id.myMapView);
    myMapView.setMapOnLongClickListener(this);
    namelist=get_sdcard_contact_data();
    if(namelist!=null) {
    }


    mylisten_getlog_Thread=new Thread(new Runnable() {
      @Override
      public void run() {
        boolean while_flag=true;
        while (while_flag) {
          mHandler_get_log.postDelayed(run_get_log_timeout, 6*1000);
          Ros_Connect.send_cmd("mark_result_request");
          try {
            Thread.sleep(10*1000);
          } catch (InterruptedException e) {
            while_flag=false;
            e.printStackTrace();
            break;
          }
        }
      }
    });
    mylisten_getlog_Thread.start();
  }
  public static SoundPool MySoundPool = null;
  public static SparseIntArray MySoundMap = null;
  protected void AddSound(){
    MySoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC,0);
    MySoundMap = new SparseIntArray();
    AssetManager manager = this.getAssets();
    try{
      int streamId;
      streamId = MySoundPool.load(manager.openFd("wav/0.wav"),1);
      MySoundMap.put(0, streamId);
      streamId = MySoundPool.load(manager.openFd("wav/1.wav"),1);
      MySoundMap.put(1, streamId);
      streamId = MySoundPool.load(manager.openFd("wav/2.wav"),1);
      MySoundMap.put(2, streamId);
      streamId = MySoundPool.load(manager.openFd("wav/3.wav"),1);
      MySoundMap.put(3, streamId);
      streamId = MySoundPool.load(manager.openFd("wav/4.wav"),1);
      MySoundMap.put(4, streamId);
      streamId = MySoundPool.load(manager.openFd("wav/5.wav"),1);
      MySoundMap.put(5, streamId);
      streamId = MySoundPool.load(manager.openFd("wav/6.wav"),1);
      MySoundMap.put(6, streamId);
      streamId = MySoundPool.load(manager.openFd("wav/7.wav"),1);
      MySoundMap.put(7, streamId);
      streamId = MySoundPool.load(manager.openFd("wav/8.wav"),1);
      MySoundMap.put(8, streamId);
      streamId = MySoundPool.load(manager.openFd("wav/ready.wav"),1);
      MySoundMap.put(9, streamId);
    }catch(IOException e){
      Toast.makeText(this, "Error Loading Sound Effects", Toast.LENGTH_SHORT).show();
    }
  }
  public  void PlaySound(int key){
    int streamId = MySoundMap.get(key);
    if(streamId>0){
      if(MySoundPool!=null) {
        MySoundPool.play(streamId, 1.0f, 1.0f, 0, 0, 1.0f);
      }
      else
      {
        Toast.makeText(this, "MySoundPool is null", Toast.LENGTH_SHORT).show();
      }
    }
  }


  public  void showInputDialog_goto(final String data_value, final String name) {
    final SelfDialog_m1 selfDialog_mapping = new SelfDialog_m1(My_map.getinstance());
    selfDialog_mapping.setTitle("确定要送餐到"+name+"餐桌吗？");
    PlaySound(1);
    selfDialog_mapping.setYesOnclickListener("确定", new SelfDialog_m1.onYesOnclickListener() {
      @Override
      public void onYesClick() {
        selfDialog_mapping.dismiss();
        My_map.getinstance().myRos_sendTextPublish.sendStringData(data_value);


        show_goto.setText("当前正前往："+name+"餐桌");
        if(name.length()<3)
          show_dangqian.setTextSize(40);
        else
          show_dangqian.setTextSize(20);
        show_dangqian.setText(name);
        PlaySound(9);
        quxiao.setBackgroundResource(R.mipmap.rocker);
        ting.setBackgroundResource(R.mipmap.rocker);
        jixu.setBackgroundResource(R.mipmap.rocker);
        et_number.setText("");
      }
    });
    selfDialog_mapping.setNoOnclickListener("取消", new SelfDialog_m1.onNoOnclickListener() {
      @Override
      public void onNoClick() {
        selfDialog_mapping.dismiss();
        show_goto.setText("");
        et_number.setText("");
      }
    });
    selfDialog_mapping.show();

  }

  private void initNINE(final String[] titles) {
    GridView gridview = (GridView) findViewById(R.id.gv_menu);
    ArrayList<HashMap<String, Object>> meumList = new ArrayList<HashMap<String, Object>>();
    for (int i = 0; i < titles.length; i++) {
      HashMap<String, Object> map = new HashMap<String, Object>();
      map.put("ItemImage", R.drawable.bt2);
      map.put("ItemText", titles[i]);
      meumList.add(map);
    }
    SimpleAdapter saMenuItem = new SimpleAdapter(this,
            meumList,
            R.layout.menuitem,
            new String[]{"ItemImage", "ItemText"},
            new int[]{R.id.ItemImage, R.id.ItemText});
    gridview.setAdapter(saMenuItem);
    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                                        String name_button=titles[arg2];
                                        for(int i=0;i<mark_coordinatejsondata_last.mark_coordinate.size();i++) {
                                          if(mark_coordinatejsondata_last.mark_coordinate.get(i).name.equals(name_button)) {
                                            String name = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).name;
                                            Float coordinate_0 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(0);
                                            Float coordinate_1 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(1);
                                            Float coordinate_2 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(2);
                                            Float coordinate_3 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(3);
                                            Float coordinate_4 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(4);
                                            Float coordinate_5 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(5);
                                            Float coordinate_6 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(6);
                                            String get_name = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).name;
                                            final String coordinate_string = String.valueOf(coordinate_0) + "," + String.valueOf(coordinate_1) + "," + String.valueOf(coordinate_2) + "," + String.valueOf(coordinate_3) + "," + String.valueOf(coordinate_4) + "," + String.valueOf(coordinate_5) + "," + String.valueOf(coordinate_6);
                                            String data_value = "simplenav:" + coordinate_string + ":" + get_name;
                                            showInputDialog_goto(data_value, name);
                                            break;
                                          }
                                        }
                                      }
                                    }

    );
  }

  public void show_layout_button()
  {
    Bean_from_slam_mark get_slam_mark_value = My_map.getinstance().mark_coordinatejsondata_last;
    int point_number=get_slam_mark_value.mark_coordinate.size();
    boolean is_have_cufang=false;
    int cufang_n=0;
    for(int i=0;i<point_number;i++)
    {
      if(get_slam_mark_value.mark_coordinate.get(i).name.equals("厨房"))
      {
        cufang_n=i;
        is_have_cufang=true;
        break;
      }
    }
    if(is_have_cufang==false) {

      show_goto.setText("请先标记厨房位置");
      my_ros_view_Layout_button.removeAllViews();
      return;
    }
    else if(point_number<=1) {
      my_ros_view_Layout_button.removeAllViews();

      show_goto.setText("请标记餐桌位置");
      return;
    }

    if(point_number>1) {
        int button_number=point_number-1;
        String[] namelist_button = new String[button_number];

        for (int i = 0; i < button_number; i++) {

            if(i<cufang_n)
              namelist_button[i] = get_slam_mark_value.mark_coordinate.get(i).name;
            else
              namelist_button[i] = get_slam_mark_value.mark_coordinate.get(i+1).name;
        }

      namelist_button=sortdemon2.sortArray(namelist_button);
      for(int i=0;i<namelist_button.length;i++){
      }
      initNINE(namelist_button);
      }
  }


  public static void showInputDialog_inputpassword() {
    final SelfDialog_a1 selfDialog_a1 = new SelfDialog_a1(My_map.getinstance());
    selfDialog_a1.setTitle("请输入管理员密码！");
    selfDialog_a1.setYesOnclickListener("确定", new SelfDialog_a1.onYesOnclickListener() {
      @Override
      public void onYesClick() {
        if(!selfDialog_a1.getInput().equals(""))
        {
          if(selfDialog_a1.getInput().equals(password))
          {
            is_first_Layout_show=false;
            show_relate_my_ros_view_Layout2_out();
            Ros_Connect.send_cmd("mark_result_request");
            selfDialog_a1.dismiss();
            left_tools_direction.setBackgroundResource(R.mipmap.btn_back);
          }
          else
            Toast.makeText(My_map.getinstance(), "密码错误！", Toast.LENGTH_LONG).show();

        }
        else
          Toast.makeText(My_map.getinstance(), "输入密码不能为空", Toast.LENGTH_LONG).show();
      }

    });
    selfDialog_a1.setNoOnclickListener("取消", new SelfDialog_a1.onNoOnclickListener() {
      @Override
      public void onNoClick() {
        selfDialog_a1.dismiss();
      }
    });
    selfDialog_a1.show();
  }

  private void findViews() {
    quxiao= (Button) findViewById(R.id.quxiao);
    quxiao.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Ros_Connect.send_cmd("空闲模式");
        quxiao.setBackgroundResource(R.mipmap.rocker_b);
        ting.setBackgroundResource(R.mipmap.rocker);
        jixu.setBackgroundResource(R.mipmap.rocker);
        PlaySound(7);

        show_goto.setText("待命状态");
      }
    });
    ting= (Button) findViewById(R.id.ting);
    ting.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if(mode.equals("simplenav")) {
          Ros_Connect.send_cmd("暂停");
          quxiao.setBackgroundResource(R.mipmap.rocker);
          ting.setBackgroundResource(R.mipmap.rocker_b);
          jixu.setBackgroundResource(R.mipmap.rocker);
          //PlaySound(5);
        }
      }
    });
    jixu= (Button) findViewById(R.id.jixu);
    jixu.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if(mode.equals("simplenav")) {
          Ros_Connect.send_cmd("继续走");//继续走
          quxiao.setBackgroundResource(R.mipmap.rocker);
          ting.setBackgroundResource(R.mipmap.rocker);
          jixu.setBackgroundResource(R.mipmap.rocker_b);
          //PlaySound(6);
        }
      }
    });

    relate_my_ros_view_Layout2 = (RelativeLayout) findViewById(R.id.my_ros_view_Layout2);
    is_first_Layout_show=true;
    my_ros_view_Layout_button = (RelativeLayout) findViewById(R.id.my_ros_view_Layout_button);
    show_goto= (TextView) findViewById(R.id.show_goto);
    show_status= (TextView) findViewById(R.id.show_status);
    show_dangqian= (TextView) findViewById(R.id.show_dangqian);
    battery = (ImageView) findViewById(R.id.battery);
    et_number= (EditText) findViewById(R.id.et_number);
    sure_number= (Button) findViewById(R.id.sure_number);
    sure_number.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        String input_get=et_number.getText().toString();
        if(!input_get.equals(""))
        {
          boolean is_have_name=false;
          for(int i=0;i<My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.size();i++)
          {
            String name=My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).name;
            if(name.equals(input_get))
            {
              Float coordinate_0 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(0);
              Float coordinate_1 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(1);
              Float coordinate_2 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(2);
              Float coordinate_3 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(3);
              Float coordinate_4 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(4);
              Float coordinate_5 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(5);
              Float coordinate_6 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(6);
              String get_name = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).name;
              final String coordinate_string = String.valueOf(coordinate_0) + "," + String.valueOf(coordinate_1) + "," + String.valueOf(coordinate_2) + "," + String.valueOf(coordinate_3) + "," + String.valueOf(coordinate_4) + "," + String.valueOf(coordinate_5) + "," + String.valueOf(coordinate_6) ;
              String data_value="simplenav:"+coordinate_string+ ":" + get_name;
              showInputDialog_goto(data_value, name);
              is_have_name=true;
              break;
            }
          }

          if(is_have_name==false)
          {
            toast(input_get+"餐桌号并不存在！");
            et_number.setText("");
          }
        }
        else
          toast("餐桌号不能为空！");

      }
    });
    left_tools_direction= (Button) findViewById(R.id.left_tools_direction);
    left_tools_direction.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         if(is_first_Layout_show==true)
        {
          showInputDialog_inputpassword();
        }
        else
        {
          left_tools_direction.setBackgroundResource(R.mipmap.setting_light_green);
          is_first_Layout_show=true;
          show_relate_my_ros_view_Layout2_in();
          myMapView.clearMapPoints();
          Ros_Connect.send_cmd("mark_result_request");
          show_layout_button();
        }
      }
    });
    show_relate_my_ros_view_Layout2_in();
  }
  private void setListener() {
  }
  private void show_relate_my_ros_view_Layout2_in()
  {
    relate_my_ros_view_Layout2.setVisibility(View.VISIBLE);
  }
  private static void show_relate_my_ros_view_Layout2_out()
  {
    relate_my_ros_view_Layout2.setVisibility(View.GONE);
  }

  public  void showInputDialog_change_point_dir_ok(String setTitle_value, final String type) {
    final SelfDialog_m1 selfDialog_mapping = new SelfDialog_m1(My_map.getinstance());
    selfDialog_mapping.setTitle(setTitle_value);
    selfDialog_mapping.setYesOnclickListener("确定", new SelfDialog_m1.onYesOnclickListener() {
      @Override
      public void onYesClick() {
        selfDialog_mapping.dismiss();
        if_need_change_point_direction=false;

      }
    });
    selfDialog_mapping.setNoOnclickListener("取消", new SelfDialog_m1.onNoOnclickListener() {
      @Override
      public void onNoClick() {
        selfDialog_mapping.dismiss();
      }
    });
    selfDialog_mapping.show();

  }


  public void onClearMapButtonClicked(View view) {
    systemCommands.reset();
    enableFollowMe();
  }

  public void onSaveMapButtonClicked(View view) {
    systemCommands.saveGeotiff();
  }

  private void toast(final String text) {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Toast toast = Toast.makeText(My_map.this, text, Toast.LENGTH_SHORT);
        toast.show();
      }
    });
  }


  private void enableFollowMe() {
    Preconditions.checkNotNull(visualizationView);

    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        visualizationView.getCamera().jumpToFrame(ROBOT_FRAME);
      }
    });
  }

  private void disableFollowMe() {
    Preconditions.checkNotNull(visualizationView);
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        visualizationView.getCamera().setFrame(MAP_FRAME);
      }
    });
  }


  public void Edit_point_ButtonClicked(final View view) {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        boolean on = ((ToggleButton) view).isChecked();
        if (on) {
          is_need_edit_point_map_show_flag=true;
          visualizationView.setVisibility(View.INVISIBLE);
          if(is_at_mapping==false&&is_switch_ros_app_mapView_big==false)
            Ros_Connect.send_cmd("mark_result_request");
        }
        else
        {
          is_need_edit_point_map_show_flag=false;
          runOnUiThread(new Runnable() {
            @Override
            public void run() {
              myMapView.clearMapPoints();
            }
          });
          visualizationView.setVisibility(View.VISIBLE);

        }
      }
    });
  }


  @Override
  public void getMapResult(OccupancyGrid message,Bitmap bitmapxxx,String map_type) {
    if(map_type.equals("static_map"))
    {
      resolution = Double.valueOf(String.valueOf(message.getInfo().getResolution()));
      final int width = message.getInfo().getWidth();
      final int height = message.getInfo().getHeight();
      map_hight = height;
      resolution_position_x = message.getInfo().getOrigin().getPosition().getX();
      resolution_position_y = message.getInfo().getOrigin().getPosition().getY();
      final int numTilesWide = (int) Math.ceil(width / (float) TextureBitmap.STRIDE);
      final int numTilesHigh = (int) Math.ceil(height / (float) TextureBitmap.STRIDE);
      final int numTiles = numTilesWide * numTilesHigh;
      final Bitmap bitmap = Bitmap.createBitmap(width,height, Bitmap.Config.RGB_565);
      int p;
        int x = 0;
        int y = 0;
        final ChannelBuffer buffer = message.getData();
        while (buffer.readable()) {
            Preconditions.checkState(y < height);
            final int tileIndex = (y / TextureBitmap.STRIDE) * numTilesWide + x / TextureBitmap.STRIDE;
            final byte pixel = buffer.readByte();
            if (pixel == -1) {
              bitmap.setPixel(x, y, Color.rgb(0, 0, 70));
            } else {
                p = 255 + (int)((-255) * pixel / 100f);
                bitmap.setPixel(x, y, Color.rgb(p,p,p));
                if (pixel < 50) {
                } else {
                }
            }
            ++x;
            if (x == width) {
              x = 0;
              ++y;
            }
        }
      Matrix m = new Matrix();
      m.postScale(1, -1);
      final Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
          WindowManager wm = Context.getWindowManager();
          int width = wm.getDefaultDisplay().getWidth();
          int height = wm.getDefaultDisplay().getHeight();
          float firstscale = (float) width / (float) newBitmap.getWidth();
          if (is_first_wait_map == true) {
            myMapView.setMapState_at_first_get_map(newBitmap, newBitmap.getWidth(), newBitmap.getHeight());
            myMapView.first_show_map_zoom(firstscale);
            is_first_wait_map = false;
            is_first_start_wait_mark_result_request = true;
            Ros_Connect.send_cmd("mark_result_request");
            new Thread(new Runnable() {
              @Override
              public void run() {
                try {
                  Thread.sleep(2000);
                } catch (InterruptedException e1) {
                  e1.printStackTrace();
                }
                while (is_first_start_wait_mark_result_request == true) {
                  Ros_Connect.send_cmd("mark_result_request");
                  try {
                    Thread.sleep(2000);
                  } catch (InterruptedException e1) {
                    e1.printStackTrace();
                  }
                }
              }
            }).start();
          } else
            myMapView.my_showMap(newBitmap, newBitmap.getWidth(), newBitmap.getHeight());
          myMapView.Refresh_show_get_new_map_picture();
        }
      });
    }
  }
  public static My_map getinstance() {
    return activity;
  }
  @Override
  public void myMapViewOnLongClick(float downX, float downY, float fingerX, float fingerY) {
    if(My_map.getinstance().in_move_point_flag==true||is_first_Layout_show==true)
      return;
    XuanfuButton_Create.createFloatView("null",downX,downY,fingerX,fingerY,"blank");
  }
  private  boolean checkIP(String str) {
    Pattern pattern = Pattern
            .compile("^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]"
                    + "|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$");
    return pattern.matcher(str).matches();
  }
  public  void showInputDialog_setInput_ip() {
    final SelfDialog_a1 selfDialog_a1 = new SelfDialog_a1(My_map.getinstance());
    selfDialog_a1.setTitle("请输入IP地址");
    //selfDialog_a1.setMessage("");
    selfDialog_a1.setYesOnclickListener("确定", new SelfDialog_a1.onYesOnclickListener() {
      @Override
      public void onYesClick() {
        if(!selfDialog_a1.getInput().equals("")&&checkIP(selfDialog_a1.getInput()))
        {
          if(mSharedPreferences!=null) {
            SharedPreferences.Editor editor = mSharedPreferences.edit();
            editor.putString("user_input_ip", selfDialog_a1.getInput());
            editor.commit();
            user_input_ip = mSharedPreferences.getString("user_input_ip", mDefaultpassword);
            My_map.getinstance().finish();
          }
          selfDialog_a1.dismiss();
        }
        else
          Toast.makeText(My_map.getinstance(), "输入IP不合法！", Toast.LENGTH_LONG).show();
      }

    });
    selfDialog_a1.setNoOnclickListener("取消", new SelfDialog_a1.onNoOnclickListener() {
      @Override
      public void onNoClick() {
        selfDialog_a1.dismiss();
      }
    });
    selfDialog_a1.show();
  }

  public  void showInputDialog_exit(String setTitle_value, final String type) {
    final SelfDialog_m1 selfDialog_mapping = new SelfDialog_m1(My_map.getinstance());
    selfDialog_mapping.setTitle(setTitle_value);
    selfDialog_mapping.setYesOnclickListener("确定", new SelfDialog_m1.onYesOnclickListener() {
      @Override
      public void onYesClick() {
        selfDialog_mapping.dismiss();
        MainActivity.getInstance().finish();
      }
    });
    selfDialog_mapping.setNoOnclickListener("取消", new SelfDialog_m1.onNoOnclickListener() {
      @Override
      public void onNoClick() {
        selfDialog_mapping.dismiss();
      }
    });
    selfDialog_mapping.show();
  }

  public static void showInputDialog_setpassword() {
    final SelfDialog_a1 selfDialog_a1 = new SelfDialog_a1(My_map.getinstance());
    selfDialog_a1.setTitle("请输入新密码！");
    selfDialog_a1.setYesOnclickListener("确定", new SelfDialog_a1.onYesOnclickListener() {
      @Override
      public void onYesClick() {
        if(!selfDialog_a1.getInput().equals(""))
        {
            if(mSharedPreferences!=null) {
              SharedPreferences.Editor editor = mSharedPreferences.edit();
              editor.putString("password", selfDialog_a1.getInput());
              editor.commit();
              password = mSharedPreferences.getString("password", mDefaultpassword);
            }
          selfDialog_a1.dismiss();
        }
        else
          Toast.makeText(My_map.getinstance(), "输入密码不能为空", Toast.LENGTH_LONG).show();
      }

    });
    selfDialog_a1.setNoOnclickListener("取消", new SelfDialog_a1.onNoOnclickListener() {
      @Override
      public void onNoClick() {
        selfDialog_a1.dismiss();
      }
    });
    selfDialog_a1.show();

  }


  public  void showInputDialog_switch_Orientation(String setTitle_value, final String type) {
    final SelfDialog_m1 selfDialog_mapping = new SelfDialog_m1(My_map.getinstance());
    selfDialog_mapping.setTitle(setTitle_value);
    selfDialog_mapping.setYesOnclickListener("确定", new SelfDialog_m1.onYesOnclickListener() {
      @Override
      public void onYesClick() {
        selfDialog_mapping.dismiss();
        if(mSharedPreferences!=null) {
          SharedPreferences.Editor editor = mSharedPreferences.edit();
          if(requestedOrientation.equals("hen")) {
            editor.putString("Orientation", "shu");
            requestedOrientation="shu";
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //竖屏
            show_layout_button();
          }
          else{
            editor.putString("Orientation", "hen");
            requestedOrientation="hen";
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
            show_layout_button();
          }
          editor.commit();
        }
      }
    });
    selfDialog_mapping.setNoOnclickListener("取消", new SelfDialog_m1.onNoOnclickListener() {
      @Override
      public void onNoClick() {
        selfDialog_mapping.dismiss();
      }
    });
    selfDialog_mapping.show();
  }

  @Override
  public void MapPoint_onClick_ListenerResult(String pointTitle,double firstX,double firstY,float fingerX, float fingerY) {
    try
    {
      if(My_map.getinstance().in_move_point_flag==true||is_first_Layout_show==true)
        return;
      My_map.getinstance().myMapView.get_marked_positionInfo_for_move_point(pointTitle,firstX, firstY, fingerX,  fingerY);
      if(in_add_more_lines_flag==true) {
        if(pointTitle.equals(in_add_more_lines_onClick_pointTitle_last)||pointTitle.equals(""))
          return;
        XuanfuButton_Create.createFloatView(pointTitle, (float) firstX, (float) firstY, fingerX, fingerY, "PointonClick_add_more_lines");
        in_add_more_lines_onClick_pointTitle_last=pointTitle;
      }
      else {
        if(!pointTitle.contains("wall"))
          XuanfuButton_Create.createFloatView(pointTitle, (float) firstX, (float) firstY, fingerX, fingerY, "PointonLongClick");
      }
    } catch (Exception e) {
    }
  }

  @Override
  public void MapPoint_onLongClick_ListenerResult(String pointTitle,double firstX,double firstY,float fingerX, float fingerY) {
    try
    {
      if(My_map.getinstance().in_move_point_flag==true||is_first_Layout_show==true)
        return;
      My_map.getinstance().myMapView.get_marked_positionInfo_for_move_point(pointTitle,firstX, firstY, fingerX,  fingerY);
      if(in_add_more_lines_flag==true) {
        if(pointTitle.equals(in_add_more_lines_onClick_pointTitle_last)||pointTitle.equals(""))
          return;
        XuanfuButton_Create.createFloatView(pointTitle, (float) firstX, (float) firstY, fingerX, fingerY, "PointonClick_add_more_lines");
        in_add_more_lines_onClick_pointTitle_last=pointTitle;
      }
      else {
        if(!pointTitle.contains("wall"))
          XuanfuButton_Create.createFloatView(pointTitle, (float) firstX, (float) firstY, fingerX, fingerY, "PointonLongClick");
      }

    }catch (Exception e) {
    }
  }
  boolean lock_change_dir=false;
  @Override
  public void OnChangeDirListenerResult(String myPointName, final float change_angle) {
    if (lock_change_dir==false)
    {
      lock_change_dir=true;
      for (int i = 0; i < My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.size(); i++) {

        final String name = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).name;
        if (myPointName.equals(name)) {
          mark_coordinate_add_succeeded = false;
          mark_coordinate_del_succeeded = false;
          change_point_dir(name, change_angle, i);
          new Thread(new Runnable() {
            @Override
            public void run() {
              for (int i = 0; i < 60; i++) {
                try {
                  Thread.sleep(500);
                } catch (InterruptedException e1) {
                  e1.printStackTrace();
                }
                if (mark_coordinate_add_succeeded == true) {
                  change_line_dir(name, change_angle);
                  break;
                }
              }
              lock_change_dir=false;
              mark_coordinate_add_succeeded = false;
            }
          }).start();
          break;
        }
      }
    }
  }

  static boolean change_line_dir(final String pointTitle, final float change_angle)
  {
    boolean the_point_is_at_line=false;
    String send_value = "";
    for (int i = 0; i < My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.size(); i++) {
      if(My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).name.equals(pointTitle)) {
        float robot_angle=0;
        if(change_angle<270)
          robot_angle=-(change_angle-90);
        else
          robot_angle=-(change_angle-90)+360;
        Double myangle=(robot_angle/180)*PI;
        Double dir_x = Math.sin(0/2)*Math.cos(0/2)*Math.cos(myangle/2)-Math.cos(0/2)*Math.sin(0/2)*Math.sin(myangle/2);
        Double dir_y = Math.cos(0/2)*Math.sin(0/2)*Math.cos(myangle/2)+Math.sin(0/2)*Math.cos(0/2)*Math.sin(myangle/2);
        Double dir_z = Math.cos(0/2)*Math.cos(0/2)*Math.sin(myangle/2)-Math.sin(0/2)*Math.sin(0/2)*Math.cos(myangle/2);
        Double dir_w = Math.cos(0/2)*Math.cos(0/2)*Math.cos(myangle/2)+Math.sin(0/2)*Math.sin(0/2)*Math.sin(myangle/2);
        Float coordinate_0 = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).coordinate.get(0);
        Float coordinate_1 = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).coordinate.get(1);
        Float coordinate_2 = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).coordinate.get(2);
        Double coordinate_3 = dir_x;
        Double coordinate_4 = dir_y;
        Double coordinate_5 = dir_z;
        Double coordinate_6 = dir_w;
        String name = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).name;
        String content = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).content;
        String line_coordinate_string = ":"+String.valueOf(coordinate_0) + "," + String.valueOf(coordinate_1) + "," + String.valueOf(coordinate_2) + "," + String.valueOf(coordinate_3) + "," + String.valueOf(coordinate_4) + "," + String.valueOf(coordinate_5) + "," + String.valueOf(coordinate_6) + ":" + name + ":" + content;
        send_value = line_coordinate_string+send_value;
        the_point_is_at_line=true;
      }
      else
      {
        Float coordinate_0 = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).coordinate.get(0);
        Float coordinate_1 = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).coordinate.get(1);
        Float coordinate_2 = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).coordinate.get(2);
        Float coordinate_3 = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).coordinate.get(3);
        Float coordinate_4 = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).coordinate.get(4);
        Float coordinate_5 = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).coordinate.get(5);
        Float coordinate_6 = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).coordinate.get(6);
        String name = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).name;
        String content = My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.get(i).content;
        String line_coordinate_string = ":"+String.valueOf(coordinate_0) + "," + String.valueOf(coordinate_1) + "," + String.valueOf(coordinate_2) + "," + String.valueOf(coordinate_3) + "," + String.valueOf(coordinate_4) + "," + String.valueOf(coordinate_5) + "," + String.valueOf(coordinate_6) + ":" + name + ":" + content;
        send_value = line_coordinate_string+send_value;
      }

    }
    if(the_point_is_at_line==false)
      return false;
    send_value = "mark:patrol_line_coordinate:" + String.valueOf(My_map.getinstance().mark_coordinatejsondata_last.patrol_line_coordinate.size() )+send_value;
    My_map.getinstance().myRos_sendTextPublish.sendStringData(send_value);
    return true;
  }

  void change_point_dir(final String name, final float change_angle, int i)
  {
    mark_coordinate_del_succeeded=false;
    final Float coordinate_0 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(0);
    final Float coordinate_1 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(1);
    Float coordinate_2 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(2);
    Float coordinate_3 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(3);
    Float coordinate_4 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(4);
    Float coordinate_5 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(5);
    Float coordinate_6 = My_map.getinstance().mark_coordinatejsondata_last.mark_coordinate.get(i).coordinate.get(6);
    final String coordinate_string = String.valueOf(coordinate_0) + "," + String.valueOf(coordinate_1) + "," + String.valueOf(coordinate_2) + "," + String.valueOf(coordinate_3) + "," + String.valueOf(coordinate_4) + "," + String.valueOf(coordinate_5) + "," + String.valueOf(coordinate_6) ;

    String data_value="mark:coordinate_del:"+coordinate_string+ ":" + name;
    My_map.getinstance().myRos_sendTextPublish.sendStringData(data_value);
    new Thread(new Runnable() {
      @Override
      public void run() {
        for(int i=0;i<30;i++)
        {

          try {
            Thread.sleep(500);
          } catch (InterruptedException e1) {
            e1.printStackTrace();
          }
          if(mark_coordinate_del_succeeded==true)
          {
            float robot_angle=0;
            if(change_angle<270)
              robot_angle=-(change_angle-90);
            else
              robot_angle=-(change_angle-90)+360;
            Double myangle=(robot_angle/180)*PI;
            Double dir_x = Math.sin(0/2)*Math.cos(0/2)*Math.cos(myangle/2)-Math.cos(0/2)*Math.sin(0/2)*Math.sin(myangle/2);
            Double dir_y = Math.cos(0/2)*Math.sin(0/2)*Math.cos(myangle/2)+Math.sin(0/2)*Math.cos(0/2)*Math.sin(myangle/2);
            Double dir_z = Math.cos(0/2)*Math.cos(0/2)*Math.sin(myangle/2)-Math.sin(0/2)*Math.sin(0/2)*Math.cos(myangle/2);
            Double dir_w = Math.cos(0/2)*Math.cos(0/2)*Math.cos(myangle/2)+Math.sin(0/2)*Math.sin(0/2)*Math.sin(myangle/2);
            mark_coordinate_add_succeeded=false;
            String data_value = "mark:coordinate_add:" + coordinate_0 + "," + coordinate_1 + ",0,"+dir_x+","+dir_y+","+dir_z+","+dir_w+":" + name;
            My_map.getinstance().myRos_sendTextPublish.sendStringData(data_value);
            break;
          }

        }
        My_map.getinstance().mark_coordinate_del_succeeded=false;
      }
    }).start();
  }
  @Override
  public void send_disableFollowMe() {
    disableFollowMe();
  }
  @Override
  protected void onStart() {
    super.onStart();
    get_permissions_and_start_updateThread();
  }

  private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
  private AlertDialog dialog;
  void get_permissions_and_start_updateThread()
  {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      int i = ContextCompat.checkSelfPermission(this, permissions[0]);
      if (i != PackageManager.PERMISSION_GRANTED) {
        showDialogTipUserRequestPermission();
      }

    }
  }
  private void showDialogTipUserRequestPermission() {
    new AlertDialog.Builder(this)
            .setTitle("存储权限不可用")
            .setMessage("由于程序升级需要获取存储空间；\n否则，您将无法正常使用本程序")
            .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                startRequestPermission();
              }
            })
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                finish();
              }
            }).setCancelable(false).show();
  }
  private void startRequestPermission() {
    ActivityCompat.requestPermissions(this, permissions, 321);
  }
  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 321&&grantResults.length!=0) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
          boolean b = shouldShowRequestPermissionRationale(permissions[0]);
          if (!b) {
            showDialogTipUserGoToAppSettting();
          } else
            finish();
        } else {
          Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();

        }
      }
    }
  }
  private void showDialogTipUserGoToAppSettting() {

    dialog = new AlertDialog.Builder(this)
            .setTitle("存储权限不可用")
            .setMessage("请在-应用设置-权限-中，允许程序使用存储权限来保存用户数据")
            .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                goToAppSetting();
              }
            })
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                finish();
              }
            }).setCancelable(false).show();
  }
  private void goToAppSetting() {
    Intent intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    Uri uri = Uri.fromParts("package", getPackageName(), null);
    intent.setData(uri);
    startActivityForResult(intent, 123);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 123) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        int i = ContextCompat.checkSelfPermission(this, permissions[0]);
        if (i != PackageManager.PERMISSION_GRANTED) {
          showDialogTipUserGoToAppSettting();
        } else {
          if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
          }
          Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
        }
      }
    }
  }
  List<String>  get_sdcard_contact_data()
  {
    ObjectInputStream ois = null;
    List<String> namelist= null;
    try {
      File file = new File("/sdcard/contact.xb");
      if(!file.exists())
        return null;
      FileInputStream fis = new FileInputStream(file);
      ois = new ObjectInputStream(fis);
      namelist = (List<String>) ois.readObject();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      try {
        if (ois != null)
        {
          ois.close();
        }
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
    return namelist;
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK){
      showInputDialog_exit("确定要退出吗？","start");
      return true;
    }
    return super.onKeyDown(keyCode, event);
  }
  @Override
  public void SetPose_event() {
  }
}
